package com.contact_book.util;

import au.com.bytecode.opencsv.CSVReader;
import au.com.bytecode.opencsv.CSVWriter;
import com.contact_book.entity.Address;
import com.contact_book.entity.Contact;
import com.contact_book.exception.FailedToHandleFileException;
import com.contact_book.operations.ContactManager;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class CSVUtil {

    private File file;

    public CSVUtil(File file) {
        this.file = file;
    }

    public void saveContacts(List<Contact> contacts)
            throws FailedToHandleFileException {
        try (
                CSVWriter writer = new CSVWriter(new FileWriter(file))) {

            writer.writeNext(ContactManager.FILE_HEADER.split(" "));
            for (Contact contact : contacts) {
                writer.writeNext(contact.toString().split("#"));
            }
        } catch (IOException ioe) {
            throw new FailedToHandleFileException(
                    "Cant't write to the file " + file.getName() + ".", ioe);
        }
    }

    public List<Contact> readContacts()
            throws FailedToHandleFileException {
        List<Contact> contacts = new ArrayList<>();
        try (
                CSVReader reader = new CSVReader(new FileReader(file))) {
            List<String[]> content = reader.readAll();
            for (int index = 1; index < content.size(); index++) {
                String[] record = content.get(index);
                Contact contact = new Contact();
                contact.setAddress(new Address());
                contact.setName(record[0]);
                contact.setEmail(record[1]);
                contact.setPhoneNumber(record[2]);
                contact.getAddress().setCity(record[3]);
                contact.getAddress().setStreet(record[4]);
                contact.getAddress().setHouseNumber(record[5]);
                contact.getAddress().setOfficeNumber(record[6]);
                contacts.add(contact);
            }
        } catch (IOException ioe) {
            throw new FailedToHandleFileException(
                    "Cant't reade the file " + file.getName() + ".", ioe);
        }
        return contacts;
    }
}
